package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.InputMismatchException;

public class OthersStudentDao01 implements BaseStudentDao {
    private static ArrayList<Student> stu = new ArrayList<>();

    static {
        try {

            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("itheima-edu-info-manager\\stu.txt"),"GBK"));
            String line;
            while ((line = br.readLine()) != null) {
                String[] splitLine = line.split(",");
                Student stuTemp = new Student(splitLine[0], splitLine[1], splitLine[2], splitLine[3]);
                stu.add(stuTemp);
            }
            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //添加
    public boolean addStudenet(Student student) {
        boolean add = stu.add(student);
        reSave();
        return add;
    }

    //查看学生
    public Student[] findAllStudent() {

        return stu.toArray(new Student[stu.size()]);
    }

    //删除学生
    public void deleteStudent(String id) {
        int index = getIndex(id);
        stu.remove(index);
        reSave();
    }

    //获取指定学号在数组中的索引
    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < stu.size(); i++) {
            if (stu.get(i) != null && id.equals(stu.get(i).getId())) {
                index = i;
            }
        }
        return index;
    }

    //修改学生
    public void updateStudent(Student student, String id) {
        int index = getIndex(id);
        stu.set(index, student);
        reSave();
    }

    private void reSave() {
        try {
            //输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("itheima-edu-info-manager\\stu.txt"), "GBK"));
            for (Student student : stu) {
                bw.write(student.toString());
                bw.newLine();
                bw.flush();
            }
            bw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
